<?php

declare(strict_types=1);

namespace app\api\controller\v1;

use app\api\BaseApiController;
use app\tpush\model\Message as MessageModel;
use app\apps\model\Apps;
use app\tpush\TPush;
use app\admin\model\Token;
use app\apps\model\Rule;
use app\apps\model\Menu;

class Message extends BaseApiController
{
    /**
     * 时间转换
     * @param int $timestamp 时间戳
     * @return string 转换后的时间格式
     */
    private function timeAgo($timestamp)
    {
        $currentTime = time();
        $date = date('Y-m-d', $timestamp);
        $date2 = date('Y-m-d', $currentTime);
        if ($date == $date2) {
            return date('H:i', $timestamp);
        } elseif (date('Y', $currentTime) == date('Y', $timestamp)) {
            return date('m-d H:i', $timestamp);
        } else {
            return date('Y-m-d H:i', $timestamp);
        }
    }

    /**
     * 消息列表
     * url: http://域名/api/v1/message/list
     * doc: http://lutui.net/doc/app/message-list.html
     */
    public function list()
    {
        $apps = MessageModel::group('app_id')->column('app_id');
        $list = Apps::with([
            'messages' => function ($query) {
                $query->where('to_uid', UID)->order('id', 'desc')->limit(1);
            },
            'versions' => function ($query) {
                $query->order('id', 'desc')->limit(1);
            }
        ])->withCount([
            'messages' => function ($query) {
                $query->where('to_uid', UID)->where('unread', 1);
            }
        ])->whereIn('id', $apps)->select();
        $new = [];
        foreach ($list as $item) {
            $message = $item->messages[0];
            $count = 0;
            if (Rule::get($item->id, 2)) {
                $count = MessageModel::where('app_id', $item->id)->where('to_uid', UID)->where('wfr', 1)->count();
            }
            $new[] = [
                'id' => $item->id,
                'name' => $item->name,
                'url' => $item->icon ? $item->icon : DOMAIN . $item->image,
                'content' => $message->title,
                'wfr' => $count > 0 ? true : false,
                'messages' => $item->messages_count,
                'time' => $this->timeAgo(strtotime($message->create_time)),
                'app' => 'app://' . $item->tag,
            ];
        }
        return json($new);
    }

    /**
     * 查看应用消息
     * url: http://域名/api/v1/message/view
     * doc: http://lutui.net/doc/app/message-view.html
     */
    public function view()
    {
        $id = $this->data['id'];
        $page = $this->data['page'];
        $tpp = 20;
        $start = ($page - 1) * $tpp;
        $list = MessageModel::with(['from'])->where('to_uid', UID)->where('app_id', $id)->order('id', 'desc')->limit($start, $tpp)->select();
        $new = [];
        $none = DOMAIN . '/static/images/none.png';
        foreach ($list as $item) {
            $new[] = [
                'id' => intval($item->id),
                'name' => $item->from->nickname,
                'url' => $item->from->avatar ? DOMAIN . $item->from->avatar : $none,
                'content' => $item->content,
                'time' => $this->timeAgo(strtotime($item->create_time)),
                'wfr' => $item->wfr == 1 ? true : false,
                'resolve' => $item->resolve ? $item->resolve : ($item->wfr == 1 ? '审核通过' : ''),
                'reject' => $item->reject ? $item->reject : ($item->wfr == 1 ? '驳回' : ''),
            ];
        }
        // 更新已读状态
        MessageModel::where('app_id', $id)->where('unread', 1)->where('to_uid', UID)->update(['unread' => 0]);
        // 发送穿透消息
        $token = Token::where('admin_id', UID)->where('platform', 'app')->value('push');
        if ($token) {
            TPush::message([$token]);
        }
        return json($new);
    }

    /**
     * 自定义菜单
     * url: http://域名/api/v1/message/menu
     * doc: http://lutui.net/doc/app/message-menu.html
     */
    public function menu()
    {
        $id = $this->data['id'];
        $app = Menu::where('app_id', $id)->find();
        if ($app && $app->menu) {
            $menu = json_decode($app->menu, true);
            $data = [];
            foreach ($menu as $item) {
                $query = [
                    'name' => $item['name'],
                    'app' => $item['sub'] ? '' : $item['url'],
                ];
                if ($item['sub']) {
                    $children = [];
                    foreach ($item['sub'] as $sub) {
                        $children[] = [
                            'name' => $sub['name'],
                            'app' => $sub['url'],
                        ];
                    }
                    $query['children'] = $children;
                }
                $data[] = $query;
            }
            if ($data) {
                return json($data);
            }
        }
        return '';
    }

    /**
     * 消息的操作
     * url: http://域名/api/v1/message/action
     * doc: http://lutui.net/doc/app/message-action.html
     */
    public function action()
    {
        $id = $this->data['id'];
        $command = $this->data['command']; // resolve=审批通过, reject=驳回请求
        // 1. 读取消息
        $message = MessageModel::find($id);
        if (empty($message)) {
            return json(['error' => '消息不存在']);
        }
        // 2. 读取应用
        $app =  Apps::find($message->app_id);
        if (empty($app)) {
            return json(['error' => '应用不存在']);
        }
        // 3. 读取权限
        $allow = Rule::get($message->app_id, 2);
        if (!$allow) {
            return json(['error' => '没有权限操作']);
        }
        $namespace = '\\app\\' . strtolower($app->tag) . '\\events\\Action@index';
        [$className, $methodName] = explode('@', $namespace);
        if (class_exists($className) && method_exists($className, $methodName)) {
            $object = new $className();
            // $message 消息, $command 操作命令
            return $object->$methodName($message, $command);
        }
        return json(['error' => '未定义操作方法']);
    }
}
